<template>
  <div class="draft-container">
    <div class="draft-header">
      <h2>我的草稿</h2>
      <p class="subtitle">管理您的新闻草稿</p>
    </div>

    <div class="draft-content">
      <!-- 操作栏 -->
      <div class="action-bar">
        <el-button type="primary" @click="createNewDraft">
          <el-icon><Plus /></el-icon>
          新建草稿
        </el-button>
        <el-button type="danger" @click="batchDelete" :disabled="selectedDrafts.length === 0">
          批量删除
        </el-button>
        <el-button @click="refreshData">刷新</el-button>
      </div>

      <!-- 草稿列表 -->
      <div class="draft-list">
        <el-table
          :data="draftList"
          v-loading="loading"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column label="封面" width="120">
            <template #default="scope">
              <img
                v-if="scope.row.picPath"
                :src="scope.row.picPath"
                class="draft-cover"
                @click="previewImage(scope.row.picPath)"
              />
              <div v-else class="no-image">无图片</div>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200">
            <template #default="scope">
              <div class="draft-title" @click="editDraft(scope.row)">
                {{ scope.row.title || '无标题草稿' }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="分类" width="100">
            <template #default="scope">
              {{ getCategoryName(scope.row.categoryId) }}
            </template>
          </el-table-column>
          <el-table-column prop="createDate" label="创建时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.createDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="modifyDate" label="修改时间" width="160">
            <template #default="scope">
              {{ formatDate(scope.row.modifyDate) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="250" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click="editDraft(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="success"
                size="small"
                @click="publishDraft(scope.row)"
              >
                发布
              </el-button>
              <el-button
                type="info"
                size="small"
                @click="previewDraft(scope.row)"
              >
                预览
              </el-button>
              <el-button
                type="danger"
                size="small"
                @click="deleteDraft(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            :page-count="pageInfo?.pages"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </div>

    <!-- 草稿预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="草稿预览"
      width="80%"
      class="preview-dialog"
    >
      <div class="preview-content" v-if="previewData">
        <h1>{{ previewData.title || '无标题草稿' }}</h1>
        <div class="preview-meta">
          <span>分类：{{ getCategoryName(previewData.categoryId) }}</span>
          <span>创建时间：{{ formatDate(previewData.createDate) }}</span>
          <span>修改时间：{{ formatDate(previewData.modifyDate) }}</span>
        </div>
        <img v-if="previewData.picPath" :src="previewData.picPath" class="preview-image" />
        <div class="preview-summary" v-if="previewData.summary">
          <h3>摘要</h3>
          <p>{{ previewData.summary }}</p>
        </div>
        <div class="preview-body" v-html="previewData.content"></div>
      </div>
    </el-dialog>

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="imagePreviewVisible"
      title="图片预览"
      width="600px"
      center
    >
      <img v-if="previewImageUrl" :src="previewImageUrl" class="preview-full-image" />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'

const router = useRouter()

// 响应式数据
const loading = ref(false)
const draftList = ref([])
const categories = ref([])
const selectedDrafts = ref([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)
const pageInfo = ref(null)

// 对话框控制
const previewVisible = ref(false)
const previewData = ref(null)
const imagePreviewVisible = ref(false)
const previewImageUrl = ref('')

// 获取草稿列表
const fetchDraftList = async () => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      authorId: localStorage.getItem('userId') || 1
    }
    
    const response = await axios.get('/app/news/draft/list', { params })
    console.log('Draft list response:', response.data)
    
    if (response.data.code === 200) {
      pageInfo.value = response.data.data
      draftList.value = pageInfo.value.list
      total.value = pageInfo.value.total
      
      // 同步页码信息
      currentPage.value = pageInfo.value.pageNum
      pageSize.value = pageInfo.value.pageSize
    } else {
      ElMessage.error(response.data.message || '获取草稿失败')
    }
  } catch (error) {
    console.error('获取草稿列表失败:', error)
    ElMessage.error('获取草稿失败，请重试')
  } finally {
    loading.value = false
  }
}

// 获取分类数据
const fetchCategories = async () => {
  try {
    const response = await axios.get('/app/categories')
    if (response.data.code === 200) {
      categories.value = response.data.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchDraftList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchDraftList()
}

// 选择处理
const handleSelectionChange = (selection) => {
  selectedDrafts.value = selection
}

// 刷新数据
const refreshData = () => {
  fetchDraftList()
}

// 工具函数
const getCategoryName = (id) => {
  const category = categories.value.find(c => c.id === id)
  return category ? category.name : '未分类'
}

const formatDate = (dateStr) => {
  if (!dateStr) return ''
  return new Date(dateStr).toLocaleString()
}

// 预览功能
const previewDraft = (draft) => {
  previewData.value = draft
  previewVisible.value = true
}

const previewImage = (url) => {
  previewImageUrl.value = url
  imagePreviewVisible.value = true
}

// 编辑草稿
const editDraft = (draft) => {
  // 将草稿数据存储到localStorage，然后在发布页面加载
  localStorage.setItem('editDraft', JSON.stringify(draft))
  router.push('/publish/news?edit=true')
}

// 发布草稿
const publishDraft = async (draft) => {
  try {
    await ElMessageBox.confirm(
      '确定要发布这个草稿吗？发布后需要管理员审核通过才能显示。',
      '确认发布',
      {
        confirmButtonText: '确定发布',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  try {
    const newsData = {
      categoryId: draft.categoryId,
      title: draft.title,
      summary: draft.summary,
      content: draft.content,
      picPath: draft.picPath,
      author: localStorage.getItem('username'),
      authorId: localStorage.getItem('userId')
    }
    
    const response = await axios.post('/app/news/publish', newsData)
    
    if (response.data.code === 200) {
      ElMessage.success('草稿发布成功，等待管理员审核')
      // 删除草稿
      await deleteDraftById(draft.id)
      fetchDraftList()
    } else {
      ElMessage.error(response.data.message || '发布失败')
    }
  } catch (error) {
    console.error('发布失败:', error)
    ElMessage.error('发布失败，请重试')
  }
}

// 删除草稿
const deleteDraft = async (draft) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个草稿吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  await deleteDraftById(draft.id)
}

const deleteDraftById = async (draftId) => {
  try {
    const response = await axios.delete(`/app/news/draft/${draftId}`)
    
    if (response.data.code === 200) {
      ElMessage.success('草稿删除成功')
      fetchDraftList()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    console.error('删除草稿失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 批量删除
const batchDelete = async () => {
  if (selectedDrafts.value.length === 0) {
    ElMessage.warning('请选择要删除的草稿')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedDrafts.value.length} 个草稿吗？删除后无法恢复。`,
      '批量删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
  } catch {
    return
  }

  const promises = selectedDrafts.value.map(draft => 
    axios.delete(`/app/news/draft/${draft.id}`)
  )

  try {
    await Promise.all(promises)
    ElMessage.success('批量删除成功')
    fetchDraftList()
  } catch (error) {
    console.error('批量删除失败:', error)
    ElMessage.error('批量删除失败')
  }
}

// 新建草稿
const createNewDraft = () => {
  // 清除可能存在的编辑数据
  localStorage.removeItem('editDraft')
  router.push('/publish/news')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories()
  fetchDraftList()
})
</script>

<style scoped>
.draft-container {
  max-width: 1400px;
  margin: 20px auto;
  padding: 20px;
}

.draft-header {
  text-align: center;
  margin-bottom: 30px;
}

.draft-header h2 {
  font-size: 28px;
  color: #333;
  margin-bottom: 10px;
}

.subtitle {
  color: #666;
  font-size: 16px;
}

.draft-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.action-bar {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  gap: 10px;
}

.draft-list {
  margin-bottom: 20px;
}

.draft-cover {
  width: 80px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.draft-cover:hover {
  transform: scale(1.05);
}

.no-image {
  width: 80px;
  height: 60px;
  background: #f5f5f5;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999;
  font-size: 12px;
  border-radius: 4px;
}

.draft-title {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
}

.draft-title:hover {
  text-decoration: underline;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 预览对话框样式 */
.preview-dialog :deep(.el-dialog__body) {
  padding: 30px;
}

.preview-content {
  max-width: 800px;
  margin: 0 auto;
}

.preview-content h1 {
  font-size: 28px;
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.preview-meta {
  color: #666;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
  font-size: 14px;
}

.preview-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  margin: 20px 0;
  border-radius: 8px;
}

.preview-summary {
  background-color: #f8f9fa;
  padding: 16px;
  border-radius: 6px;
  margin: 20px 0;
  border-left: 4px solid #409eff;
}

.preview-summary h3 {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.preview-summary p {
  margin: 0;
  color: #666;
  line-height: 1.6;
}

.preview-body {
  line-height: 1.8;
  color: #333;
  margin: 20px 0;
}

.preview-full-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
}
</style> 